package com.whut.transportation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.whut.transportation.adapter.TransinfoAdapter;
import com.whut.transportation.adapter.TransinfoAdapter.MyClickListener;
import com.whut.transportation.entity.AllTransInfo;
import com.whut.transportation.entity.GuDao;
import com.whut.transportation.entity.Message;
import com.whut.transportation.entity.TransInfo;
import com.whut.transportation.network.HttpManager;
import com.whut.transportation.network.HttpRequestVo;
import com.whut.transportation.parser.JSONParser;
import com.whut.transportation.ui.BaseActivity;
import com.whut.transportation.ui.BaseActivity.DataCallback;
import com.whut.transportation.utils.Constant;
/**
 * 卸车界面
 */
public class TransInfoSckActivity extends BaseActivity implements MyClickListener{
	
	private ListView transinfo;//列表显示信息
	private List<TransInfo> transinfos;//服务器取回的数据
	private TransinfoAdapter transinfoAdapter;//将数据和显示条目绑定的自定义适配器
	private List<TransInfo> onlyOneTypeTransinfos;
	private GuDao gudao;
	private SharedPreferences preferences;
	private boolean checkSelect = true;

	private Button input; // 提交
	private Button allSelect; //全选
	private List<Integer> listItemID = new ArrayList<Integer>();
	
	//private SwipeRefreshLayout mSwipeLayout; 
	private boolean result =false;
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		//点击加载更多按钮，从服务器取下一页的代码
		case R.id.btn_add_more:
			getData(false);
			break;
		case R.id.input:   
			minput();
            break;
		case R.id.allselect:
			if(checkSelect){
				checkSelect = false;
				selectAll();
				allSelect.setText("全不选");
			} else {
				checkSelect = true;
				noSelectAll();
				allSelect.setText("全选");
			}
			break;
		default:
			break;
		}
		super.onClick(v);
	}
	
	
	/**
	 * 取消全选
	 */
	private void noSelectAll() {
		for(int i=0;i<transinfos.size();i++){
			transinfoAdapter.mcheck.set(i, false);
			transinfoAdapter.notifyDataSetChanged();
		}
	}
	/**
	 * 全选
	 */
	private void selectAll() {
		for(int i=0;i<transinfos.size();i++){
			transinfoAdapter.mcheck.set(i, true);
			transinfoAdapter.notifyDataSetChanged();
		}
	}
	
	private void minput() {
		listItemID.clear();
		for(int i=0;i<transinfoAdapter.getMcheck().size();i++){
			if(transinfoAdapter.getMcheck().get(i)){
				listItemID.add(i);
			}
		}
		if(listItemID.size()==0){
			Toast.makeText(mContext, "未选中任何条目无法执行批量检查", Toast.LENGTH_SHORT).show();
		} else {
			StringBuilder sb = new StringBuilder("[");
			for (int i = 0; i < listItemID.size(); i++) {
				int flag = transinfos.get(listItemID.get(i)).getFlag();
				if(flag==0){
					transinfos.get(listItemID.get(i)).setFlag(1);
				} else if(flag==2){
					transinfos.get(listItemID.get(i)).setFlag(3);
				}
				sb.append("{\"shunhao\":\"").append(onlyOneTypeTransinfos.get(listItemID.get(i)).getNumber()).append("\",");
				sb.append("\"id\":\"").append(onlyOneTypeTransinfos.get(listItemID.get(i)).getId()).append("\",");
				sb.append("\"chehao\":\"").append(onlyOneTypeTransinfos.get(listItemID.get(i)).getTrainNumber()).append("\",");
				sb.append("\"chezhong\":\"").append(onlyOneTypeTransinfos.get(listItemID.get(i)).getTrain()).append("\"");
				sb.append("},");
			}
			sb.deleteCharAt(sb.length() - 1);
			sb.append("]");
			String mdata = sb.toString();
			String daima = onlyOneTypeTransinfos.get(0).getDaima();
			HttpRequestVo vo = new HttpRequestVo();
			vo.requestUrl = Constant.M_UPDATE_OR_SAVE;
			vo.context = mContext;
			HashMap<String, String> req = new HashMap<String, String>();
			req.put("mdata", mdata);
			req.put("daima", daima);
			req.put("type", "1");// 0表示装车1卸车
			req.put("account", preferences.getString("account", null));// 0表示装车
			req.put("name", preferences.getString("name", null));// 0表示装车
			vo.requestDataMap = req;
			vo.parser = new JSONParser(Message.class);
			getDataFromServer(HttpManager.POST_MOTHOD, vo,
					new DataCallback<HashMap<String, Object>>() {
						@Override
						public void onStart() {
						}
						@Override
						public void onFailed() {
							showNetErrorDialog();
						}
						@Override
						public void processData(
								HashMap<String, Object> paramObject,
								boolean paramBoolean) {
							Intent transInfoActivity = new Intent(TransInfoSckActivity.this,TransInfoSckActivity.class);
							transInfoActivity.putExtra("gudao", gudao);
							startActivity(transInfoActivity);
							Toast.makeText(mContext, "车辆检查成功，请进行装车信息录入",Toast.LENGTH_SHORT).show();
							finish();
						}
						@Override
						public void onFinish() {
							closeProgressDialog();
						}
					});
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (transinfoAdapter != null) {
			onlyOneTypeTransinfos.clear();
			onlyOneTypeTransinfos.addAll(transinfos);
			transinfoAdapter.notifyDataSetChanged();
		} else {
			getData(false);
		}
	}
	@Override
	protected void loadViewLayout() {
		setContentView(R.layout.activity_transinfo);
		setTitleBarView(true, "卸车", -1, true);
		preferences = getSharedPreferences("userId", Context.MODE_PRIVATE);
		Intent intent = getIntent();
		gudao = (GuDao) intent.getSerializableExtra("gudao");
	}
	@Override
	protected void findViewById() {
		transinfo = (ListView) findViewById(R.id.transinfo);
		input =(Button) findViewById(R.id.input);
		allSelect = (Button) findViewById(R.id.allselect);
		//mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.id_swipe_ly);
	}

	@Override
	protected void afterFindViewId() {
		transinfos = new ArrayList<TransInfo>();
		onlyOneTypeTransinfos = new ArrayList<TransInfo>();
	}

	@Override
	protected void processLogic() {
	}

	@Override
	protected void setListener() {
		//transinfo.setOnItemClickListener(new OnItemClick());
		input.setOnClickListener(this);
		allSelect.setOnClickListener(this);
	/*	mSwipeLayout.setOnRefreshListener(this);
		mSwipeLayout.setColorScheme(android.R.color.holo_blue_bright, android.R.color.holo_green_light,  
                android.R.color.holo_orange_light, android.R.color.holo_red_light);*/
	}

	@Override
	protected void getDataAgain() {
		
	}
	private void getData(final boolean isRefresh) {
		HttpRequestVo vo = new HttpRequestVo();
		vo.requestUrl = Constant.ALL_SCK_TRANPORTATION_INFO;
		vo.context = mContext;
		HashMap<String, String> req = new HashMap<String, String>();
		req.put("account",preferences.getString("account", null));
		req.put("gudao", gudao.getGudao());
		req.put("quming", preferences.getString("quming_1", null));
		vo.requestDataMap = req;
		vo.parser = new JSONParser(AllTransInfo.class);
		getDataFromServer(HttpManager.POST_MOTHOD, vo, 
				new DataCallback<HashMap<String, Object>>() {
					@Override
					public void onStart() {
					}
					@Override
					public void onFailed() {
						showNetErrorDialog();
					}
					@Override
					public void processData(
							HashMap<String, Object> paramObject,
							boolean paramBoolean) {
						int code = (Integer)paramObject.get("code");
						if(code == 1){
							AllTransInfo allTransInfo = (AllTransInfo) paramObject.get("result");
							if(isRefresh){
								transinfos.clear();
								onlyOneTypeTransinfos.clear();
							}
							transinfos.addAll(allTransInfo.ListTransportInfo);
							onlyOneTypeTransinfos.addAll(allTransInfo.ListTransportInfo);
							if(transinfo.getAdapter()==null){
								transinfoAdapter = new TransinfoAdapter(mContext,onlyOneTypeTransinfos,TransInfoSckActivity.this,preferences.getString("account", null),preferences.getString("name", null));
								transinfo.setAdapter(transinfoAdapter);
							} else {
								transinfoAdapter.notifyDataSetChanged();
							}
						} else {
							Toast.makeText(mContext, "目前数据为空", Toast.LENGTH_LONG).show();
						}
					}
					@Override
					public void onFinish() {
						closeProgressDialog();
					}
				});
	}
	/**
	 * 注册listView条目单击事件的监听
	 * @author yuliyan
	 */
	public class OnItemClick implements OnItemClickListener{
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
				TransInfo transinfo = transinfos.get(position);
				if(transinfo.getFlag()==2){
					Intent carCheckSecondActivity = new Intent(TransInfoSckActivity.this,CarCheckSecondActivity.class);
					carCheckSecondActivity.putExtra("transinfo", transinfo);
					startActivity(carCheckSecondActivity);
				} else if(transinfo.getFlag()==1){
					Intent unLoad = new Intent(TransInfoSckActivity.this,UnloadDetailActivity.class);
					unLoad.putExtra("transinfo", transinfo);
					startActivity(unLoad);
				} else if(transinfo.getFlag()==0){
					Intent carCheckActivity = new Intent(TransInfoSckActivity.this, CarCheckActivity.class);
					carCheckActivity.putExtra("transinfo", transinfo);
					startActivity(carCheckActivity);
				}
			}
	}
	
	public GuDao getGudao() {
		return gudao;
	}

	@Override
	public boolean clickListener(View v, Integer tag,int i) {
		if(i==0||i==1){
			baoDian(tag,i);
		} else if(i==2){
			TransInfo transinfo = transinfos.get(tag);
			if (transinfo.getFlag() == 3) {
				Intent carCheckSecondActivity = new Intent(TransInfoSckActivity.this,CarCheckSecondActivity.class);
				carCheckSecondActivity.putExtra("transinfo", transinfo);
				startActivity(carCheckSecondActivity);
			} else if (transinfo.getFlag() == 1||transinfo.getFlag() == 2) {
				buildAlertDialog_input(transinfo);
			} else if (transinfo.getFlag() == 0){
				Intent carCheckActivity = new Intent(TransInfoSckActivity.this,CarCheckActivity.class);
				carCheckActivity.putExtra("transinfo", transinfo);
				startActivity(carCheckActivity);
			}
		}
		return result;
	}
	/**
	 * 弹出施封篷布号的对话框
	 * @param transinfo
	 */
	private void buildAlertDialog_input(final TransInfo transinfo) {
		final EditText inputServer = new EditText(this);
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    builder.setTitle("施封篷布号").setIcon(android.R.drawable.ic_dialog_info).setView(inputServer)
	            .setNegativeButton("取消", null);
	    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
	
	        public void onClick(DialogInterface dialog, int which) {
	           updateTaskInfo(null,inputServer.getText().toString(),transinfo);
	         }
	    });
	    builder.show();
	 }
	/**
	 * 更新施封篷布号
	 * @param in_time
	 * @param bu_number
	 * @param transinfo
	 */
	private void updateTaskInfo(String in_time,String bu_number,TransInfo transinfo) {
		HttpRequestVo vo = new HttpRequestVo();
		vo.requestUrl = Constant.UPDATE_TASK_SCK_INFO;
		vo.context = mContext;
		vo.parser = new JSONParser(Message.class);
		HashMap<String, String> req = new HashMap<String, String>();
		req.put("account", preferences.getString("account", null));
		req.put("id", transinfo.getId());
		req.put("taskStyle", String.valueOf(transinfo.getType()));
		req.put("shunhao", transinfo.getNumber());
		req.put("taskInfo.tarpaulinId", bu_number);
		vo.requestDataMap = req;
		getDataFromServer(HttpManager.POST_MOTHOD, vo, 
				new DataCallback<HashMap<String, Object>>() {
				@Override
				public void onStart() {
					showProgressDialog(getResources().getString(
							R.string.loading_content));
				}
				@Override
				public void onFailed() {
					showNetErrorDialog();
				}
				@Override
				public void processData(
						HashMap<String, Object> paramObject,
						boolean paramBoolean) {
					Message message = (Message) paramObject.get("result");
					if(message.getMessage() == 1){
						Toast.makeText(mContext, "提交成功", Toast.LENGTH_SHORT).show();
					}
				}
				@Override
				public void onFinish() {
					closeProgressDialog();
				}
		});
	}
	/**
	 * 报点
	 * @param tag
	 * @param i
	 */
	public void baoDian(Integer tag,int i){
		TransInfo transInfo = onlyOneTypeTransinfos.get(tag);
		String mdata = "{shunhao:\""+transInfo.getNumber()+"\",id:\""+transInfo.getId()+"\",chehao:\""+transInfo.getTrainNumber()+"\",chezhong:\""+transInfo.getTrain()+"\"}";
		HttpRequestVo vo = new HttpRequestVo();
		vo.requestUrl = Constant.BAODIAN;
		vo.context = mContext;
		HashMap<String, String> req = new HashMap<String, String>();
		req.put("mdata", mdata);
		req.put("daima", transInfo.getDaima());
		req.put("type", "0");// 0表示装车
		req.put("flag", String.valueOf(i));
		req.put("account",preferences.getString("account", null));// 0表示装车
		req.put("name",preferences.getString("name", null));// 0表示装车
		vo.requestDataMap = req;
		vo.parser = new JSONParser(Message.class);
		getDataFromServer(HttpManager.POST_MOTHOD, vo,
				new DataCallback<HashMap<String, Object>>() {
					@Override
					public void onStart() {
					}
					@Override
					public void onFailed() {
						showNetErrorDialog();
					}
					@Override
					public void processData(
							HashMap<String, Object> paramObject,
							boolean paramBoolean) {
						Message message = (Message) paramObject.get("result");
						if(message.getMessage()==1){
							Toast.makeText(mContext, "第一次车辆还未检查，不可报点", Toast.LENGTH_SHORT).show();
							result = false;
						} else if(message.getMessage()==2){
							Toast.makeText(mContext, "报点已完成", Toast.LENGTH_SHORT).show();
							result = false;
						} else if(message.getMessage()==3){
							Toast.makeText(mContext, "开始报点成功", Toast.LENGTH_SHORT).show();
							result = true;
						} else if(message.getMessage()==4){
							Toast.makeText(mContext, "完了报点成功", Toast.LENGTH_SHORT).show();
							result = true;
						} else if(message.getMessage()==5){
							Toast.makeText(mContext, "请进行结束报点", Toast.LENGTH_SHORT).show();
							result = false;
						} else if(message.getMessage()==6){
							Toast.makeText(mContext, "请进行开始报点", Toast.LENGTH_SHORT).show();
							result = false;
						}
					}
					@Override
					public void onFinish() {
						closeProgressDialog();
					}
				});
		
	}
}
